﻿using Models.ApiModel;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BLL;
using System.Web;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Models.webReq;
using SqlSugar;
using System.Configuration;
using Models.ApiModel.req;
using WHC.Framework.Commons;
using Tools;

namespace webui.Controllers
{
    public class ApiCarController : ApiController
    {
        Car_carInfoBLL carBll = new Car_carInfoBLL();
        Car_BrandBLL brabdBll = new Car_BrandBLL();
        Car_imgBLL carimgBLL = new Car_imgBLL();
        UserInfoBLL userbll = new UserInfoBLL();
        string host = ConfigurationSettings.AppSettings["httpip"];

        //新增
        [VerifyKeyAttribute]
        public BaseRes AddCar(Car_carInfo car)
        {
            BaseRes res = new BaseRes();
            res.Code = 0;
            if (string.IsNullOrEmpty(car.brandName) || car.brandId == 1)
            {
                res.Msg = "品牌不能为空";
                return res;
            }
            if (string.IsNullOrEmpty(car.xingHao))
            {
                res.Msg = "型号不能为空";
                return res;
            }
            if (car.showPrice == 0)
            {
                res.Msg = "显示价格不能为空";
                return res;
            }
            if (car.Carimgs.Length<1)
            {
                res.Msg = "请上传图片";
                return res;
            }
            string userstr = Base64Util.Decrypt(car.Token);
            Token user = userstr.ToObject<Token>();
            car.firstImg = car.Carimgs[0];
            car.createtime = DateTime.Now;
            car.sellState = (int)BaseNeum.normall;// 默认状态。0 删除，1正常， 2下架，3已卖掉
            car.CreateUserID = user.Userid;
            car.CreateUser = user.UserName;
            UserInfo dbuser= userbll.GetById(user.Userid);
            car.shopid = dbuser.Shopid;
            car.ShopName = dbuser.ShopName; //设置默认店铺
            int carid = carBll.InsertReturnIdentity(car); //得到主键id
            Car_img[] imgarr = new Car_img[car.Carimgs.Length];
            for (int i = 0; i < car.Carimgs.Length; i++)
            {
                Car_img img = new Car_img { Imgurl = car.Carimgs[i] };
                img.carinfoId = carid;
                imgarr[i] = img;
                img.isfirst = i == 0 ? true : false;
            }
            carimgBLL.InsertRange(imgarr);
            res.Code = 1;
            res.Msg = "成功";
            return res;
        }

        //获取品牌
        [HttpGet]
        public BaseRes GetBrand()
        {
            BaseRes res = new BaseRes();
            var list = brabdBll.GetList().OrderBy(u => u.OrderNum).ToList(); ;
            string[] str = new string[list.Count] ;
            for (int i = 0; i < list.Count; i++)
            {
                str[i] = list[i].BrandName;
            }
            res.Data = str;
            return res;
        }


        public BaseRes UpLoadImg()
        {
            BaseRes res = new BaseRes();
           
            HttpPostedFile file = HttpContext.Current.Request.Files["file"];//接收
            string ext = Path.GetExtension(file.FileName);//文件后缀名
            string[] LimitPictureType = new string[] { ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" };
            if (LimitPictureType.Contains(ext.ToUpper()))
            {
                try
                {
                    string _newFileName = Guid.NewGuid().ToString();
                    string _dbPicturePath = "AppUpImg/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                    string _toServerPicturePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _dbPicturePath);
                    string imgfullname = _toServerPicturePath + _newFileName + ext;
                    res.Data = _dbPicturePath+ _newFileName + ext; //保存数据库的
                    if (!Directory.Exists(_toServerPicturePath))
                    {
                        Directory.CreateDirectory(_toServerPicturePath);
                    } 
                    file.SaveAs(imgfullname);
                    res.Code = 1;
                }
                catch (Exception ce)
                {
                    res.Code = 0;
                    res.Msg = ce.Message;
                    Tools.CommonHellper.WriteLog(ce.Message + ce.StackTrace);
                }
               
            }
            else
            {
                res.Code = 0;
                res.Msg = "图片格式不对";
            }
             
            return res;
        }

    
        //查询车辆集合
        [HttpPost]
        public BaseRes QueryCarList(CarCondition carcondtion)
        {
            BaseRes res = new BaseRes();
          
        
            #region 多条件

            //if (carcondtion.id > 0)
            //{
            //    liswhere.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = carcondtion.id.ToString() });
            //}
            //if (carcondtion.years > 1)
            //{
            //    liswhere.Add(new ConditionalModel() { FieldName = "years", ConditionalType = ConditionalType.Equal, FieldValue = carcondtion.years.ToString() });
            //}
            //if (carcondtion.brandId > 0)
            //{
            //    liswhere.Add(new ConditionalModel() { FieldName = "brandId", ConditionalType = ConditionalType.Equal, FieldValue = carcondtion.brandId.ToString() });
            //}
            //if (!string.IsNullOrEmpty(carcondtion.brandName))
            //{
            //    liswhere.Add(new ConditionalModel() { FieldName = "brandName", ConditionalType = ConditionalType.Equal, FieldValue = carcondtion.brandName });
            //}
            //if (!string.IsNullOrEmpty(carcondtion.xingHao))
            //{
            //    liswhere.Add(new ConditionalModel() { FieldName = "xingHao", ConditionalType = ConditionalType.Like, FieldValue = carcondtion.xingHao });
            //}
            //if (carcondtion.engineCC > 0)
            //{
            //    liswhere.Add(new ConditionalModel() { FieldName = "engineCC", ConditionalType = ConditionalType.Equal, FieldValue = carcondtion.engineCC.ToString() });
            //}
            //if (carcondtion.hasT != null)
            //{
            //    liswhere.Add(new ConditionalModel() { FieldName = "xingHao", ConditionalType = ConditionalType.Equal, FieldValue = carcondtion.hasT == true ? "1" : "0" });
            //}
            //if (!string.IsNullOrEmpty(carcondtion.speedAssembly))
            //{
            //    liswhere.Add(new ConditionalModel() { FieldName = "speedAssembly", ConditionalType = ConditionalType.Equal, FieldValue = carcondtion.speedAssembly });
            //}
            //if (null != carcondtion.jQXDaoQi)
            //{
            //    liswhere.Add(new ConditionalModel() { FieldName = "jQXDaoQi", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = carcondtion.jQXDaoQi.ToString() });
            //}
            //if (null != carcondtion.sYxDaoQi)
            //{
            //    liswhere.Add(new ConditionalModel() { FieldName = "sYxDaoQi", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = carcondtion.sYxDaoQi.ToString() });
            //}
            //if (null != carcondtion.showTxt)
            //{
            //    liswhere.Add(new ConditionalModel() { FieldName = "sYxDaoQi", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = carcondtion.sYxDaoQi.ToString() });
            //}
            //if (!string.IsNullOrEmpty(carcondtion.showTxt))
            //{
            //    liswhere.Add(new ConditionalModel() { FieldName = "showTxt", ConditionalType = ConditionalType.Like, FieldValue = carcondtion.showTxt });
            //} 
            #endregion
            
            if (carcondtion.PageSize == 0)
            {
                carcondtion.PageSize = 10;
            }
            if (carcondtion.PageIndex == 0)
            {
                carcondtion.PageIndex = 1;
            }
            PageModel pg = new PageModel() { PageIndex = carcondtion.PageIndex, PageSize = carcondtion.PageSize };
            List<Car_carInfo> list = new List<Car_carInfo>();
            List<IConditionalModel> liswhere = new List<IConditionalModel>();
            liswhere.Add(new ConditionalModel() { FieldName = "sellState", ConditionalType = ConditionalType.Equal, FieldValue = "1" });

            if (!string.IsNullOrEmpty(carcondtion.keyword))
            {
                liswhere.Add(new ConditionalCollections()
                {
                    ConditionalList =
                    new List<KeyValuePair<WhereType, SqlSugar.ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>
                        ( WhereType.And ,
                        new ConditionalModel() { FieldName = "brandName", ConditionalType = ConditionalType.Like, FieldValue = carcondtion.keyword }),
                        new  KeyValuePair<WhereType, ConditionalModel>
                        (WhereType.Or,
                        new ConditionalModel() { FieldName = "xingHao", ConditionalType = ConditionalType.Like, FieldValue = carcondtion.keyword })
                    }
                }); 
              
            }
            if (!string.IsNullOrEmpty(carcondtion.speedAssembly))
            {
                if (carcondtion.speedAssembly == "手动")
                {
                    liswhere.Add(new ConditionalModel() { FieldName = "speedAssembly", ConditionalType = ConditionalType.Equal, FieldValue = "手动" });
                }
                else
                {
                    liswhere.Add(new ConditionalModel() { FieldName = "speedAssembly", ConditionalType = ConditionalType.NoEqual, FieldValue = "手动" });
                }
            }
            if (carcondtion.minPrice>0)
            {
                liswhere.Add(new ConditionalModel() { FieldName = "showPrice", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = carcondtion.minPrice.ToString() });
            }
            if (carcondtion.maxPrice > 0)
            {
                liswhere.Add(new ConditionalModel() { FieldName = "showPrice", ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = carcondtion.maxPrice.ToString() });
            }
            if (!string.IsNullOrEmpty(carcondtion.ShopName))
            {
                
                    liswhere.Add(new ConditionalModel() { FieldName = "ShopName", ConditionalType = ConditionalType.Like, FieldValue = carcondtion.ShopName });
            }

            list = carBll.GetPageList(liswhere, pg, s => s.id, OrderByType.Desc);
            for (int i = 0; i < list.Count; i++)
            {
                list[i].firstImg = host + list[i].firstImg;

            }
            var result = new { count = pg.PageCount, data = list };
            res.Code = 1;
            res.Data = result;
            return res;
        }

        //获取一个车
        [HttpPost]
        public BaseRes GetCarByid(ReqCar req)
        {
            BaseRes res = new BaseRes();
            if (req!=null && req.ID>0)
            {
                Car_carInfo  car = carBll.GetById(req.ID);
                if (car!= null)
                {
                    //查询图片
                  List<Car_img> imglist=  carimgBLL.GetList(u => u.carinfoId == req.ID ).OrderByDescending(s=> s.isfirst).ToList();
                    car.Carimgs = new string[imglist.Count];

                    string userstr = Base64Util.Decrypt(req.Token);
                    Token user = userstr.ToObject<Token>();

                    for (int i = 0; i < imglist.Count; i++)
                    {
                        car.Carimgs[i] = host + imglist[i].Imgurl;
                        if (user!=null && user.RoleName == "店长" && user.Shopid==car.shopid)
                        {
                            continue;
                        }
                        else if (user !=null && user.Userid==car.CreateUserID)
                        {
                            continue; //自己发布的车允许修成本价
                        }
                        else if (user != null && (user.RoleName == "销售" || user.RoleName == "店长"))
                        {
                            car.costPrice = 0; //成本价格
                        }
                        else
                        {
                            car.costPrice = 0;
                            car.sellPrice = 0;
                            car.closePrice = 0; // 成交价
                            car.hideTxt = "";
                        }
                        
                    }
                    res.Data = car;
                    res.Msg = "查询成功";
                }
                else
                {
                    res.Code = 0;
                    res.Msg = "ID错误";
                }
            }
            else
            {
                res.Code = 0;
                res.Msg = "ID错误";
            }
            return res;
        
        }
        
        //获取一个用户的车
        [HttpPost]
        public BaseRes GetCarByUserID(CarCondition carcondtion) 
        {
            BaseRes res = new BaseRes();

            
            if (carcondtion.PageSize == 0)
            {
                carcondtion.PageSize = 10;
            }
            if (carcondtion.PageIndex == 0)
            {
                carcondtion.PageIndex = 1;
            }
            PageModel pg = new PageModel() { PageIndex = carcondtion.PageIndex, PageSize = carcondtion.PageSize };
        


            string userstr = Base64Util.Decrypt(carcondtion.Token);
            Token user = userstr.ToObject<Token>();
            if (user==null)
            {
                res.Code = 0;
                res.Msg = "没有权限";
                return res;
            }
            
            List<Car_carInfo> list = new List<Car_carInfo>();
            if (string.IsNullOrEmpty(carcondtion.keyword))
            {
                List<IConditionalModel> liswhere = new List<IConditionalModel>();
                liswhere.Add(new ConditionalModel() { FieldName = "sellState", ConditionalType = ConditionalType.NoEqual, FieldValue = "0" });
                liswhere.Add(new ConditionalModel() { FieldName = "CreateUserID", ConditionalType = ConditionalType.Equal, FieldValue = user.Userid.ToString() });
                list = carBll.GetPageList(liswhere, pg, s => s.id, OrderByType.Desc);
            }
            else
            {
                list = carBll.GetPageList(u => u.sellState != 0 && u.CreateUserID== user.Userid  && (u.brandName.Contains(carcondtion.keyword) || u.xingHao.Contains(carcondtion.keyword)), pg, s => s.id, OrderByType.Desc);
            }

            for (int i = 0; i < list.Count; i++)
            {
                list[i].firstImg = host + list[i].firstImg;
            }
            var result = new { count = pg.PageCount, data = list };
            res.Code = 1;
            res.Data = result;
            return res;
        }

        //修改一辆车
        [VerifyKeyAttribute]
        public BaseRes EditCar(Car_carInfo car)
        {
            BaseRes res = new BaseRes();
            res.Code = 0;
            if (car.id==0)
            {
                res.Msg = "ID不能为空";
                return res;
            }
            if (string.IsNullOrEmpty(car.brandName) )
            {
                res.Msg = "品牌不能为空";
                return res;
            }
            if (string.IsNullOrEmpty(car.xingHao))
            {
                res.Msg = "型号不能为空";
                return res;
            }
            if (car.showPrice == 0)
            {
                res.Msg = "显示价格不能为空";
                return res;
            }
            if (car.regdate == null)
            {
                res.Msg = "请输入上户日期";
                return res;
            }
            if (car.Carimgs.Length < 1)
            {
                res.Msg = "请上传图片";
                return res;
            }
             Car_carInfo dbcar= carBll.GetById(car.id);

            string userstr = Base64Util.Decrypt(car.Token);
            Token user = userstr.ToObject<Token>();
            if (user.RoleName == "店长" || user.Userid==dbcar.CreateUserID)
            {
                
                Car_img[] imgarr = new Car_img[car.Carimgs.Length];
                for (int i = 0; i < car.Carimgs.Length; i++)
                {
                    if (car.Carimgs[i].Contains(host))
                    {
                        car.Carimgs[i] = car.Carimgs[i].Replace(host,""); //删掉HTTP。
                    }
                    Car_img img = new Car_img { Imgurl = car.Carimgs[i] };
                    img.carinfoId = dbcar.id;
                    imgarr[i] = img;
                    img.isfirst = i == 0 ? true : false;

                }

                dbcar.firstImg = car.Carimgs[0];
                dbcar.ModifyUserID = user.Userid;
                dbcar.ModifyUser = user.UserName;
                dbcar.brandName = car.brandName;
                dbcar.xingHao = car.xingHao;
                dbcar.Wkm = car.Wkm;
                dbcar.regdate = car.regdate;
                dbcar.engineCC = car.engineCC;
                dbcar.hasT = car.hasT;
                dbcar.speedAssembly = car.speedAssembly;
                dbcar.jQXDaoQi = car.jQXDaoQi;
                dbcar.sYxDaoQi  = car.sYxDaoQi;
                dbcar.costPrice = car.costPrice;
                dbcar.showPrice = car.showPrice;
                dbcar.sellPrice = car.sellPrice;
                dbcar.showTxt = car.showTxt;
                dbcar.hideTxt = car.hideTxt;
                dbcar.brandName = car.brandName;
                dbcar.Modifytime = DateTime.Now;
                carBll.Update(dbcar);
                carimgBLL.Delete(s => s.carinfoId == car.id);
                carimgBLL.InsertRange(imgarr);
                res.Code = 1;
                res.Msg = "修改成功";
            }
            else
            {
                res.Msg = "没有权限，修改";
                return res;
            }


           
            return res;
        }


        //下架
        [VerifyKeyAttribute]
        public BaseRes pullDown(Car_carInfo car)
        {
            BaseRes res = new BaseRes();
            res.Code = 0;
            if (car.id == 0)
            {
                res.Msg = "ID不能为空";
                return res;
            }
            Car_carInfo dbcar = carBll.GetById(car.id);
            string userstr = Base64Util.Decrypt(car.Token);
            Token user = userstr.ToObject<Token>();
            if (user.RoleName == "店长" || user.Userid == dbcar.CreateUserID)//自己或店长才能修改
            {
                if (car.closePrice > 0)
                {
                    dbcar.sellState = (int)BaseNeum.selled;
                    dbcar.closePrice = car.closePrice;
                    dbcar.DudectMoney = car.DudectMoney;
                    dbcar.sellUserName = car.sellUserName;//提出人；
                    dbcar.CloseTime = DateTime.Now;
                }
                else
                {
                    dbcar.sellState = (int)BaseNeum.pullDown;
                }
                carBll.Update(dbcar);
                res.Code = 1;
                res.Msg = "修改成功";
            }
            else
            {
                res.Msg = "没有权限，修改";
                return res;
            }
            return res;
        }

        //删除
        [VerifyKeyAttribute]
        public BaseRes Del(Car_carInfo car)
        {
            BaseRes res = new BaseRes();
            res.Code = 0;
            if (car.id == 0)
            {
                res.Msg = "ID不能为空";
                return res;
            }
            Car_carInfo dbcar = carBll.GetById(car.id);
            string userstr = Base64Util.Decrypt(car.Token);
            Token user = userstr.ToObject<Token>();
            if (user.RoleName == "店长" || user.Userid == dbcar.CreateUserID)
            {
                dbcar.sellState = (int)BaseNeum.del;
                carBll.Update(dbcar);
                res.Code = 1;
                res.Msg = "删除成功";
            }
            else
            {
                res.Msg = "没有权限，修改";
                return res;
            }
            return res;
        }

        //上架
        [VerifyKeyAttribute]
        public BaseRes UpShelf(Car_carInfo car)
        {
            BaseRes res = new BaseRes();
            res.Code = 0;
            if (car.id == 0)
            {
                res.Msg = "ID不能为空";
                return res;
            }
            Car_carInfo dbcar = carBll.GetById(car.id);
            string userstr = Base64Util.Decrypt(car.Token);
            Token user = userstr.ToObject<Token>();
            if (user.RoleName == "店长" || user.Userid == dbcar.CreateUserID)
            {
                if (dbcar.sellState != (int)BaseNeum.normall)
                {
                    dbcar.sellState = (int)BaseNeum.normall;
                    carBll.Update(dbcar);
                }
                res.Code = 1;
                res.Msg = "上架成功";
            }
            else
            {
                res.Msg = "没有权限，修改";
                return res;
            }
            return res;
        }



        [HttpGet]
        public BaseRes GetshopUser(int shopid)
        {
            BaseRes res = new BaseRes();
            
            var list = userbll.GetList(u=> u.Shopid==shopid); 
            string[] str = new string[list.Count];
            for (int i = 0; i < list.Count; i++)
            {
                str[i] = list[i].username;
            }
            res.Data = str;
            return res;
        }
        

        [VerifyKeyAttribute]
        public string Gets2(string sf)
        {
            //http://localhost:23586/api/apicar/gets2?sf=sdfs
            return sf + "f车";
        }

        public string Gets()
        {
            return "f车khjkhg";
        }


    }
}
